package com.whc.gulimall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whc.common.utils.PageUtils;
import com.whc.common.utils.Query;
import com.whc.gulimall.product.dao.BrandDao;
import com.whc.gulimall.product.dao.CategoryBrandRelationDao;
import com.whc.gulimall.product.dao.CategoryDao;
import com.whc.gulimall.product.entity.CategoryBrandRelationEntity;
import com.whc.gulimall.product.service.CategoryBrandRelationService;
import com.whc.gulimall.product.vo.BrandVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author angaoen
 */
@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {

    /**
     * 品牌 Dao
     */
    @Resource
    private BrandDao brandDao;

    /**
     * 商品三级分类 Dao
     */
    @Resource
    private CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<CategoryBrandRelationEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取品牌关联的分类
     *
     * @param brandId 品牌id
     * @return 分类列表
     */
    @Override
    public List<CategoryBrandRelationEntity> listCategory(Long brandId) {
        return baseMapper
                .selectList(new QueryWrapper<CategoryBrandRelationEntity>().eq("brand_id", brandId));
    }

    /**
     * 新增品牌关联分类
     *
     * @param categoryBrandRelation 品牌关联分类
     */
    @Override
    public void saveCategoryBrandRelation(CategoryBrandRelationEntity categoryBrandRelation) {
        // 获取品牌id
        Long brandId = categoryBrandRelation.getBrandId();
        // 获取分类id
        Long catelogId = categoryBrandRelation.getCatelogId();

        // 设置属性
        categoryBrandRelation.setBrandName(brandDao.selectById(brandId).getName());
        categoryBrandRelation.setCatelogName(categoryDao.selectById(catelogId).getName());

        // 保存
        save(categoryBrandRelation);
    }

    /**
     * 获取分类关联的品牌
     *
     * @param catId 分类id
     * @return 品牌
     */
    @Override
    public List<BrandVo> listBrandsByCatId(Long catId) {
        List<CategoryBrandRelationEntity> entities = baseMapper
                .selectList(new QueryWrapper<CategoryBrandRelationEntity>().eq("catelog_id", catId));
        return CollUtil.isNotEmpty(entities) ? BeanUtil.copyToList(entities, BrandVo.class) : null;
    }

}
